﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using tuwien.auto.eibclient;
using System.Globalization;
using KNXFramework.Logging;

namespace KNXFramework.KNXObjects.ValueObjects
{
    internal class TimeObjectValue : IValueObject
    {
        private DateTime m_Value = DateTime.MinValue;
        private int m_WeekDay = 0;
           
        #region Constructors

        public TimeObjectValue(string value)
        {
            if (value.ToLower() == "now")
            {
                if (DateTime.Now.DayOfWeek != DayOfWeek.Sunday)
                    m_WeekDay = (int)DateTime.Now.DayOfWeek;
                else
                    m_WeekDay = 7;

                m_Value = DateTime.Now;
                return;
            }
            if (!DateTime.TryParseExact(value, "H:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.NoCurrentDateDefault, out m_Value))
                throw new ApplicationException("TimeObjectValue cannot parse value as datetime. Val : " + value);
        }
        public TimeObjectValue(EIBBuffer buffer)
        {
            if (buffer.data.Length < 5)
            {
                CustomLogger.WriteErrorEntry("Invalid packed received for TimeObject (too short)");
                return;
            }
            int day = (buffer.data[2] & 0xe0) >> 5;
            int hour = (byte)(buffer.data[2] & 0x1f);
            int min = buffer.data[3];
            int sec = buffer.data[4];

            m_Value = new DateTime(1, 1, 1, hour, min, sec);            
            m_WeekDay = day;
            
        }
        public TimeObjectValue()
        {
        }

        #endregion

        public override string ToString()
        {
            if (m_Value != DateTime.MinValue)
                return m_Value.ToString("hh:mm:ss");
            else
                return "now";
        }

        #region IValueObject Members

        public void AdaptBufferBeforeSending(bool isWrite, tuwien.auto.eibclient.EIBBuffer buffer)
        {
            byte[] b = new byte[5];
            b[0] = buffer.data[0];
            b[1] = buffer.data[1];
            b[2] = Convert.ToByte(((m_WeekDay << 5) & 0xe0) | (m_Value.Hour & 0x1f));
            b[3] = (byte)m_Value.Minute;
            b[4] = (byte)m_Value.Second;
            buffer.data = b;
        }

        #endregion

        #region IEquatable<IValueObject> Members

        public bool Equals(IValueObject other)
        {
            TimeObjectValue otherVal = other as TimeObjectValue;
            bool equality = false;
            if (otherVal != null)
                equality = m_Value.Equals(otherVal.m_Value);

            return equality;
        }

        #endregion
    }
}
